package pkg;

import java.util.Calendar;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.TextConstruct;

public class BaseService {
	
	public static boolean addNewUser(String name, String number, String email, String group, BaseEngine engine){
		if (name==null || number == null || email==null || group==null)
			return false;
		if (!email.contains("@"))
			return false;
		
		GoogleBaseEntry entry = new GoogleBaseEntry();
		entry.setTitle(TextConstruct.create(TextConstruct.Type.TEXT, name, null));
		entry.setDraft(true);
		entry.getGoogleBaseAttributes().setItemType("System users");
		entry.getGoogleBaseAttributes().addTextAttribute("number", number);
		entry.getGoogleBaseAttributes().addTextAttribute("e-mail", email);
		entry.getGoogleBaseAttributes().addReferenceAttribute("group", group);
		return engine.insertGoogleBaseEntry(entry);
	}
	
	public static String printUserList(BaseEngine engine){
		StringBuffer out = new StringBuffer();
		out.append("<h2>Lista uzytkownikow</h2>\n");
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault().getItemsFeedURL());
		query.setStringCustomParameter("Item Type", "System users");
		GoogleBaseFeed feed = engine.getQueryResult(query);
		if (feed==null) return out.toString();
		
		out.append("<TABLE border=1>\n");
		out.append("\t<tr>\n");
		out.append("\t\t<td>"+"Nazwisko Imie"+"</td>\n");
		out.append("\t\t<td>"+"Numer indeksu"+"</td>\n");
		out.append("\t\t<td>"+"E-mail"+"</td>\n");
		out.append("\t\t<td>"+"Grupa"+"</td>\n");
		out.append("\t<tr>\n");
		for (GoogleBaseEntry entry : feed.getEntries()) {
			if (entry.getGoogleBaseAttributes().getItemType().equals("System users")){
			out.append("\t<tr>");
			out.append("\t\t<td>");
			out.append(entry.getTitle().getPlainText());
			out.append("</td>\n");
			
			out.append("\t\t<td>");
			out.append(entry.getGoogleBaseAttributes().getTextAttribute("number"));
			out.append("</td>\n");
			
			out.append("\t\t<td>");
			out.append(entry.getGoogleBaseAttributes().getTextAttribute("e-mail"));
			out.append("</td>\n");
			
			out.append("\t\t<td>");
			String tmp = entry.getGoogleBaseAttributes().getReferenceAttribute("group");
			out.append(tmp);
			/*GoogleBaseQuery queryGroup = new GoogleBaseQuery(FeedURLFactory.getDefault().getItemsFeedURL());
			query.setStringCustomParameter("Item Type", "System groups");
			GoogleBaseFeed feedGroup = engine.getQueryResult(queryGroup);
			for (GoogleBaseEntry entryGroup : feedGroup.getEntries()){
			if (entryGroup!=null)
				if (entryGroup.getId().equals(tmp))
					out.append(entryGroup.getTitle().getPlainText());
			}*/
			out.append("</td>\n");
			
			out.append("\t</tr>");
			}
		}
		
		out.append("</TABLE>");
		return out.toString();
	}
}
